﻿using System.Web.Mvc;
using System.Web.Routing;
using Castle.MicroKernel.Registration;
using Castle.Windsor;
using Castle.Windsor.Installer;
using EBE.COM.Core.Interfaces;
using EBE.COM.Infrastructure.Data;
using EBE.COM.Web.Plumbing;

namespace EBE.COM.Web
{
  public class MvcApplication : System.Web.HttpApplication
  {
    // see: http://stw.castleproject.org/Default.aspx?Page=Windsor-tutorial-ASP-NET-MVC-3-application-To-be-Seen&NS=Windsor&AspxAutoDetectCookieSupport=1
    private static IWindsorContainer _container;

    private static void BootstrapContainer()
    {
      _container = new WindsorContainer().Install(FromAssembly.This());
      RegisterRepositories();

      var controllerFactory = new WindsorControllerFactory(_container.Kernel);
      ControllerBuilder.Current.SetControllerFactory(controllerFactory);
    }

    private static void RegisterRepositories()
    {
      const string connectionString = @"Data Source=li-211\SQLEXPRESS; Integrated Security=true; User Instance=true; AttachDBFilename=|DataDirectory|\EBECOMDB.mdf; Initial Catalog=EBECOMDB;";

      _container.Register(Component.For<IRepository<ICategory>>()
        .ImplementedBy<CategoryRepository>()
        .DependsOn(new { connectionString = connectionString }));

      _container.Register(Component.For<IRepository<ISubCategory>>()
        .ImplementedBy<SubCategoryRepository>()
        .DependsOn(new { connectionString = connectionString }));
    }

    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
      filters.Add(new HandleErrorAttribute());
    }

    public static void RegisterRoutes(RouteCollection routes)
    {
      routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

      routes.IgnoreRoute("{*favicon}", new { favicon = @"(.*/)?favicon.ico(/.*)?" });

      routes.MapRoute(
          "Default", // Route name
          "{controller}/{action}/{id}", // URL with parameters
          new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
      );
    }

    protected void Application_Start()
    {
      AreaRegistration.RegisterAllAreas();

      RegisterGlobalFilters(GlobalFilters.Filters);
      RegisterRoutes(RouteTable.Routes);

      ControllerBuilder.Current.DefaultNamespaces.Add("EBE.COM.Web.Controllers");
      //ControllerBuilder.Current.DefaultNamespaces.Add("EBE.COM.Web.Areas.Admin.Controllers");

      BootstrapContainer();
    }

    protected void Application_End()
    {
      _container.Dispose();
    }
  }
}